/**
 * @brief 使用TIM14设计1ms中断服务函数
 */
#include "api_timer.h"
#include "main.h"
#include "time.h"
#include "button.h"

TIM_HandleTypeDef htim14;

#define IF_TIMEOUT_EXECUTE(timer_event_tick, timer_out, _do) \
    timer_event_tick++;                                      \
    if (timer_event_tick == timer_out)                       \
    {                                                        \
        timer_event_tick = 0;                                \
        _do;                                                 \
    }

void MX_TIM14_Init(void)
{
    TIM_OC_InitTypeDef sConfigOC = {0};

    htim14.Instance = TIM14;
    htim14.Init.Prescaler = 48 - 1; // 分频到1MHz
    htim14.Init.CounterMode = TIM_COUNTERMODE_UP;
    htim14.Init.Period = 1000 - 1; // 1ms中断
    htim14.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
    htim14.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE;

    if (HAL_TIM_Base_Init(&htim14) != HAL_OK)
    {
        Error_Handler();
    }

    // 启动定时器中断
    HAL_TIM_Base_Start_IT(&htim14);
}

void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *tim_baseHandle)
{

    if (tim_baseHandle->Instance == TIM14)
    {
        /* USER CODE BEGIN TIM14_MspInit 0 */

        /* USER CODE END TIM14_MspInit 0 */
        /* TIM14 clock enable */
        __HAL_RCC_TIM14_CLK_ENABLE();

        /* TIM14 interrupt Init */
        HAL_NVIC_SetPriority(TIM14_IRQn, 0, 0);
        HAL_NVIC_EnableIRQ(TIM14_IRQn);
        /* USER CODE BEGIN TIM14_MspInit 1 */

        /* USER CODE END TIM14_MspInit 1 */
    }
}

void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *tim_baseHandle)
{

    if (tim_baseHandle->Instance == TIM14)
    {
        /* USER CODE BEGIN TIM14_MspDeInit 0 */

        /* USER CODE END TIM14_MspDeInit 0 */
        /* Peripheral clock disable */
        __HAL_RCC_TIM14_CLK_DISABLE();

        /* TIM14 interrupt Deinit */
        HAL_NVIC_DisableIRQ(TIM14_IRQn);
        /* USER CODE BEGIN TIM14_MspDeInit 1 */

        /* USER CODE END TIM14_MspDeInit 1 */
    }
}

static uint16_t _keypad_scan_tick_count = 0;

void TIM14_IRQHandler_Callback(void)
{
    IF_TIMEOUT_EXECUTE(_keypad_scan_tick_count, KEYPAD_SCAN_TIME_SERVE, timer_keypad_scan_callback());
}
